﻿<%@ WebHandler Language="C#" Class="allotHouseMangager" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;

public class allotHouseMangager : AjaxHandlerBase
{
    public allotHouseMangager()
    {
        htTypePermit.Add("add", Constants.Permit_Allot_Add);
        htTypePermit.Add("attach", Constants.Permit_Attach_Add);
    }

    override public void RequestProcess(HttpContext context)
    {
        string strOp = context.Request["op"];
        string strResponse = "";
        switch (strOp.ToLower())
        {
            case "getlist":     //页面查询结果集Table
                strResponse = getlist(context);
                break;
            case "add":         //添加分配
                strResponse = add(context);
                break;
            case "gethouselist":        //根据查询显示房源明细
                strResponse = gethouselist(context);
                break;
            case "getallooptype":       //判断下拉框验证（到店/人）
                strResponse = check(context);
                break;
            case "attach":          //房源所属
                strResponse = attach(context);
                break;
            default:
                break;
        }
        context.Response.ContentType = "text/plain";
        context.Response.Buffer = true;
        context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        context.Response.Write(strResponse);
    }

    
    //房源归属
    private string attach(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.House_AllotLogs model = (Chenxin.Lib.House.Entity.House_AllotLogs)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_AllotLogs));
            string houseid = context.Request["houseIdList"];
            string usercode = context.Request["usercode"];

            //根据工号得到员工
            Chenxin.Lib.Passport.Entity.Hr_UserInfo hruse = null;
            hruse = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetEntityByCode(usercode);
            if (hruse == null)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "该工号不存在！");
            model.NowPersonID = hruse.UserId;
            model.NowPerson = hruse.UserName;

            if (model.NowCityId == Guid.Empty || model.NowCompanyId == Guid.Empty || model.NowDepartID == Guid.Empty || model.NowPersonID == Guid.Empty)
            {
                return string.Format("{{success:'0',msg:'请填写完整数据,目标城市、公司、部门、人员都不能为空！',data:''}}");
            }

            int flg = HouseByHand(houseid, model);
            if (1 == flg)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "没有可分配的房源！");
            }
            else
            {
                AddLog("" + CurrentUserInfo.UserName + "手动分配房源:已分配给人[" + model.NowPerson + "]",
                           OperationType.OperationTypeComboList()["OprType_HouseAllot"].ToString());
            }
            return string.Format("{{success:'1',msg:'{0}',data:''}}", "分配成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
    

    private string check(HttpContext context)
    {
        try
        {
            if (CurrentUserInfo.ContainsPermit(Chenxin.Lib.Utility.Constants.Permit_Allot_Depart_AllUser))
                return "{success:1,msg:'',data:{byuser:false}}";
            else
                return "{success:1,msg:'',data:{byuser:true}}";
        }
        catch (Exception ex)
        {
            return "{success:0,msg:'" + ex.Message + "',data:{byuser:true}}";
        }
    }
    
    //查询分配记录结果集
    private string getlist(HttpContext context)
    {
        try
        {
            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数

            string fieldlist = "RecordID,HouseCode,HouseAddress,OldPerson,OldDepart,OldCompany,OldCity,NowPerson,NowDepart,NowCompany,NowCity,OperPerson,OperTime";
            string fieldtablelist = "RecordID,HouseCode,HouseAddress,OldPerson,OldDepart,OldCompany,OldCity,NowPerson,NowDepart,NowCompany,NowCity,OperPerson,OperTime";
            string orderfield = "House_AllotLogs.OperTime desc";

            Guid cityId = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid companyId = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid areaId = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaId"]);
            Guid departId = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            //判断权限范围/////////////////////////////////////////////
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (OperPersonID = '{0}') ", userId);
            else if (departId != Guid.Empty)
                sb.AppendFormat(" AND (OperDepartId = '{0}')", departId);
            else if (areaId != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, areaId);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(areaId);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null) return string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失");

                sb.AppendFormat(" AND (OperDepartId in (select departId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (companyId != Guid.Empty)
                sb.AppendFormat(" AND OperCompanyId = '{0}'", companyId);
            else if (cityId != Guid.Empty)
                sb.AppendFormat(" AND OperCityId = '{0}'", cityId);
            else
                sb.AppendFormat(" AND OperCompanyId = '{0}'", CurrentUserInfo.CompanyId); 
            
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            //查看所有分配房源权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllAllotHouse))
            {
                sb1.Append(" (1=1) ");
            }
            //查看城市分配房源权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityAllotHouse))
            {
                sb1.AppendFormat(" OperCityId= '{0}' ", CurrentUserInfo.CityId);
            }
            //查看公司分配房源权限
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCompanyAllotHouse))
            {
                sb1.AppendFormat(" OperCompanyId= '{0}' ", CurrentUserInfo.CompanyId);
            }
            //查看部门分配房源权限
            //else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewDepartAllotHouse))
            //{
            //    sb1.Append("EXISTS(");
            //    sb1.Append("Select 1 from v_Struct_UserDepartRelation M ");
            //    sb1.AppendFormat("WHERE (House_AllotLogs.OperDepartId = M.Departid AND  M.Userid= '{0}') ", CurrentUserInfo.UserId);
            //    sb1.Append(")");
            //}
            else
            {
                sb1.AppendFormat(" OperPersonID = '{0}'", CurrentUserInfo.UserId);
            }
            
            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            string stime = context.Request.QueryString["stime"];
            string etime = context.Request.QueryString["etime"];
            string usercode = context.Request.QueryString["usercode"];

            if (!String.IsNullOrEmpty(stime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,OperTime,120)),120)  >= '{0}'", (stime)));
            }
            if (!String.IsNullOrEmpty(etime))
            {
                sb1.Append(string.Format(" AND convert(varchar(10),(convert(datetime,OperTime,120)),120)  <= '{0}'", (etime)));
            }
            if (!String.IsNullOrEmpty(usercode))
            {
                sb1.Append(string.Format(" and OldPersonID=(select userid from v_Hr_User_BaseInfo where usercode='{0}')", usercode));
            }

            //判断权限范围结束////////////////////////////////////////////
            System.Data.DataSet list = null;
            list = Chenxin.Lib.House.DAL.House_RequestChangeInfo.GetList(
                iPageIndex, iPageSize, orderfield, "House_AllotLogs", sb1.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)list.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetKeyListHtml(list, out strHtml))
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误:" + strHtml);
            }
            list.Dispose();
            list = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

    /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
    private bool GetKeyListHtml(System.Data.DataSet dslist, out string strHtml)
    {
        try
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<table height=\"100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\" style=\"width:920px;\">");
            sb.Append("<thead><tr>");
            sb.Append("<th width=\"100\">房源编号</th>");
            sb.Append("<th width=\"100\">房源地址</th>");
            sb.Append("<th width=\"60\" >原所属人</th>");
            sb.Append("<th width=\"60\" >原门店</th>");
            sb.Append("<th width=\"60\" >原公司</th>");
            sb.Append("<th width=\"60\" >原城市</th>");
            sb.Append("<th width=\"60\">现所属人</th>");
            sb.Append("<th width=\"60\">现门店</th>");
            sb.Append("<th width=\"60\" >现公司</th>");
            sb.Append("<th width=\"60\" >现城市</th>");
            sb.Append("<th width=\"60\">操作人</th>");
            sb.Append("<th width=\"80\">操作时间</th>");
            sb.Append("</tr></thead><tbody>");
                int i=0;
            foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
            {
                
                if(i%2==0)
                    sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist\">", row["RecordID"].ToString());
                else
                    sb.AppendFormat("<tr id=\"{0}\" class=\"tr_houselist bluebgcolor\">", row["RecordID"].ToString());
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseCode", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "HouseAddress", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OldPerson", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OldDepart", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OldCompany", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OldCity", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "NowPerson", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "NowDepart", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "NowCompany", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "NowCity", ""));
                sb.AppendFormat("<td>{0}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OperPerson", ""));
                sb.AppendFormat("<td>{0:yyyy-MM-dd}</td>", Chenxin.Lib.Utility.DatasetHelper.GetValue(row, "OperTime",""));

                sb.Append("</tr>");
                i++;
            }

            sb.Append("</tbody></table>");
            strHtml = sb.ToString();
            return true;
        }
        catch (Exception ex)
        {
            strHtml = ex.Message;
            return false;
        }
    }
    
     /// <summary>
    /// 返回列表；
    /// 根据查询参数生成查询条件1,根据权限设定生成查询条件2；
    /// 返回Json数据：{count:'30',data:'abc'}
    /// </summary>
    /// <param name="context"></param>
     private string add(HttpContext context)
    {
        try
        {
            string allotStyle = context.Request["allotStyle"];
            Chenxin.Lib.House.Entity.House_AllotLogs model = (Chenxin.Lib.House.Entity.House_AllotLogs)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.House_AllotLogs));


            if (model.NowCityId == Guid.Empty || model.NowCompanyId == Guid.Empty || model.NowDepartID == Guid.Empty )
            {
                return string.Format("{{success:'0',msg:'请填写完整数据,目标城市、公司、部门都不能为空！',data:''}}");
            }

            if (model.NowDepartID != model.OldDepartID)
            {
                if (!CurrentUserInfo.ContainsPermit(Constants.Permit_AllotHouse_Over))
                {
                    return string.Format("{{success:'0',msg:'不能夸门店转房源！',data:''}}");
                }
            }
            
            if(!string.IsNullOrEmpty(model.NowPerson))
                model.NowPerson = model.NowPerson.Remove(model.NowPerson.IndexOf("("));
            if(!string.IsNullOrEmpty(model.OldPerson))
                model.OldPerson = model.OldPerson.Remove(model.OldPerson.IndexOf("("));
            
            //快速分配
            if("10".Equals(allotStyle)) {
                
                string allotType = context.Request["allotType"];
                
                //人
                if ("10".Equals(allotType))
                {
                    if (!HouseToUser(model))
                    {
                        return string.Format("{{success:'0',msg:'{0}',data:''}}", "没有可分配的房源！");
                    }
                    else
                    {
                        AddLog("" + CurrentUserInfo.UserName + "快速分配房源:已分配给人[" + model.NowPerson + "]",
                                OperationType.OperationTypeComboList()["OprType_HouseAllot"].ToString());
                    }
                }//店
                else if ("20".Equals(allotType))
                {
                    if (!HouseToDep(model))
                    {
                        return string.Format("{{success:'0',msg:'{0}',data:''}}", "没有可分配的房源！");
                    }
                    else
                    {
                        AddLog("" + CurrentUserInfo.UserName + "快速分配房源:已全部分配给店[" + model.NowDepart + "]",
                                OperationType.OperationTypeComboList()["OprType_HouseAllot"].ToString());
                    }
                }
                //平均 
                else {
                    int flg = HouseToAvg(model);
                    if(1==flg)
                    {
                      return string.Format("{{success:'0',msg:'{0}',data:''}}", "没有可分配的房源！");
                    }
                    else if (2 == flg)
                    {
                        return string.Format("{{success:'0',msg:'{0}',data:''}}", "接受门店没有可接受的员工！");
                    }
                    else
                    {
                        AddLog("" + CurrentUserInfo.UserName + "快速分配房源:已平均分配给店[" + model.NowDepart + "]",
                                   OperationType.OperationTypeComboList()["OprType_HouseAllot"].ToString());                        
                    }
                }
            } else {
                    string houseid = context.Request["houseIdList"];
                    int flg = HouseByHand(houseid, model);
                    if(1==flg) {
                        return string.Format("{{success:'0',msg:'{0}',data:''}}", "没有可分配的房源！");
                    } else {
                        AddLog("" + CurrentUserInfo.UserName + "手动分配房源:已分配给人[" + model.NowPerson + "]",
                                   OperationType.OperationTypeComboList()["OprType_HouseAllot"].ToString()); 
                    }            
            }            
           return string.Format("{{success:'1',msg:'{0}',data:''}}", "分配成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

     //快速分配房源给某人
     private bool HouseToUser(Chenxin.Lib.House.Entity.House_AllotLogs model)
     {
         StringBuilder sb = new StringBuilder();
         string str="";
         if (model.OldPersonID != null && model.OldPersonID != Guid.Empty)
             str = string.Format(" and House_BaseInfo.OprPersonId='{0}'", model.OldPersonID.ToString());
         string strSql = "";
         //添加房源分配日志并修改原房源记录
         strSql += String.Format("insert into House_AllotLogs select newid(),HouseId,HouseCode,Community+BuildingName+Room,OprPersonId,OprPerson,house_baseinfo.cityid,city,house_baseinfo.CompanyId,house_baseinfo.CompanyName,OprDepartId,OprDepart,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}',getdate() from house_baseinfo left join v_Hr_DepartmentInfo on(v_Hr_DepartmentInfo.departid= house_baseinfo.CompanyId) where OprDepartId='{16}'{17};", model.NowPersonID.ToString(), model.NowPerson, model.NowCityId.ToString(), model.NowCity, model.NowCompanyId.ToString(), model.NowCompany, model.NowDepartID.ToString(), model.NowDepart, CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.CityId.ToString(), CurrentUserInfo.CityName, CurrentUserInfo.CompanyId.ToString(), CurrentUserInfo.CompanyName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, model.OldDepartID.ToString(),str);
         strSql += string.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',Customer_BaseInfo.CompanyId='{4}',Customer_BaseInfo.CompanyName='{5}',CityId='{8}',CityName='{9}' from dbo.Customer_BaseInfo,house_baseinfo where house_baseinfo.CustomerId=Customer_BaseInfo.CustomerId and House_BaseInfo.OprDepartId='{6}'{7};", model.NowPerson, model.NowPersonID.ToString(), model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, model.OldDepartID.ToString(), str, model.NowCityId.ToString(), model.NowCity);

         strSql += String.Format("update House_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',CompanyId='{4}',CompanyName='{5}',CityId='{6}' where OprDepartId='{7}'{8};", model.NowPerson, model.NowPersonID.ToString(), model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, model.NowCityId.ToString(), model.OldDepartID.ToString(),str);


         return Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
     }

     //快速分配房源给某店
     private bool HouseToDep(Chenxin.Lib.House.Entity.House_AllotLogs model)
     {
         StringBuilder sb = new StringBuilder();
         string str = "";
         if (model.OldPersonID != null && model.OldPersonID != Guid.Empty)
             str = string.Format(" and House_BaseInfo.OprPersonId='{0}'", model.OldPersonID.ToString());
         string strSql = "";

         //添加房源分配日志并修改原房源记录
         strSql += String.Format("insert into House_AllotLogs select newid(),HouseId,HouseCode,Community+BuildingName+Room,OprPersonId,OprPerson,house_baseinfo.cityid,city,house_baseinfo.CompanyId,house_baseinfo.CompanyName,OprDepartId,OprDepart,OprPersonId,OprPerson,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}',getdate() from house_baseinfo left join v_Hr_DepartmentInfo on(v_Hr_DepartmentInfo.departid= house_baseinfo.CompanyId) where  OprDepartId='{14}'{15};", model.NowCityId.ToString(), model.NowCity, model.NowCompanyId.ToString(), model.NowCompany, model.NowDepartID.ToString(), model.NowDepart, CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.CityId.ToString(), CurrentUserInfo.CityName, CurrentUserInfo.CompanyId.ToString(), CurrentUserInfo.CompanyName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, model.OldDepartID.ToString(),str);
         strSql += string.Format("update Customer_BaseInfo set OprDepart='{0}',OprDepartId='{1}',Customer_BaseInfo.CompanyId='{2}',Customer_BaseInfo.CompanyName='{3}',CityId='{6}',CityName='{7}' from dbo.Customer_BaseInfo,house_baseinfo where house_baseinfo.CustomerId=Customer_BaseInfo.CustomerId and House_BaseInfo.OprDepartId='{4}'{5};", model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, model.OldDepartID.ToString(), str, model.NowCityId.ToString(), model.NowCity);

         strSql += String.Format("update House_BaseInfo set OprDepart='{0}',OprDepartId='{1}',CompanyId='{2}',CompanyName='{3}',CityId='{4}' where OprDepartId='{5}'{6};", model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, model.NowCityId.ToString(),model.OldDepartID.ToString(),str);

        return  Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
     }
    
     //平均分配房源
     private int HouseToAvg(Chenxin.Lib.House.Entity.House_AllotLogs model)
     {
         StringBuilder sb = new StringBuilder();
         string housecount_sql = "OprDepartId='"+model.OldDepartID.ToString()+"'";
         if (model.OldPersonID != null && model.OldPersonID != Guid.Empty)
             housecount_sql += " and OprPersonId='" + model.OldPersonID.ToString()+"'"; 
         string usercount_sql = String.Format("DepartId='{0}' and Status='1' and IsVirtual='0' and validate=1 "
            +"and userid in (select UserId from dbo.Struct_UserDepartRelation where DepartId='{0}' and isbelong=1 and IsRoleA=1)", model.NowDepartID.ToString());
         DataSet house_ds = Chenxin.Lib.House.DAL.House_BaseInfo.GetList(housecount_sql);
         DataSet user_ds = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetList(usercount_sql);
         int house_sum = house_ds.Tables[0].Rows.Count;
         int user_sum = user_ds.Tables[0].Rows.Count;

          if (house_sum == 0)
             return 1;
         else if (user_sum == 0)
             return 2;
         else
         {
             string str = "";
             for (int i = 0; i < house_sum; )
             {
                 for (int j = 0; j < user_sum; j++)
                 {
                     if (i >= house_sum)
                         break;
                     //添加房源分配日志并修改原房源记录
                     str += String.Format("insert into House_AllotLogs select newid(),HouseId,HouseCode,Community+BuildingName+Room,OprPersonId,OprPerson,house_baseinfo.cityid,city,house_baseinfo.CompanyId,house_baseinfo.CompanyName,OprDepartId,OprDepart,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}',getdate() from house_baseinfo left join v_Hr_DepartmentInfo on(v_Hr_DepartmentInfo.departid= house_baseinfo.CompanyId) where HouseId='{16}';", user_ds.Tables[0].Rows[j]["UserId"], user_ds.Tables[0].Rows[j]["UserName"], model.NowCityId.ToString(), model.NowCity, model.NowCompanyId.ToString(), model.NowCompany, model.NowDepartID.ToString(), model.NowDepart, CurrentUserInfo.UserId, CurrentUserInfo.UserName, CurrentUserInfo.CityId.ToString(), CurrentUserInfo.CityName, CurrentUserInfo.CompanyId.ToString(), CurrentUserInfo.CompanyName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, house_ds.Tables[0].Rows[i]["HouseId"]);
                     str += string.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',Customer_BaseInfo.CompanyId='{4}',Customer_BaseInfo.CompanyName='{5}',CityId='{7}',CityName='{8}' from dbo.Customer_BaseInfo,house_baseinfo where house_baseinfo.CustomerId=Customer_BaseInfo.CustomerId and House_BaseInfo.HouseId='{6}';", user_ds.Tables[0].Rows[j]["UserName"], user_ds.Tables[0].Rows[j]["UserId"], model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, house_ds.Tables[0].Rows[i]["HouseId"], model.NowCityId.ToString(), model.NowCity);

                     str += string.Format("update House_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',CompanyId='{4}',CompanyName='{5}',CityId='{6}'  where HouseId='{7}';", user_ds.Tables[0].Rows[j]["UserName"], user_ds.Tables[0].Rows[j]["UserId"], model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany,model.NowCityId.ToString(), house_ds.Tables[0].Rows[i]["HouseId"]);

                     i++;
                 }
             }
             bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(str);
             if (flag)
                return 0;
             else
                 return 1;
         }
     }

     //手动分配房源给某人
     private int HouseByHand(string houseid, Chenxin.Lib.House.Entity.House_AllotLogs model)
     {
         string strSql = "";
         houseid = houseid.Replace(",", "','");
         //添加房源分配日志并修改原房源记录
         strSql += String.Format("insert into House_AllotLogs select newid(),HouseId,HouseCode,Community+BuildingName+Room,OprPersonId,OprPerson,house_baseinfo.cityid,city,house_baseinfo.CompanyId,house_baseinfo.CompanyName,OprDepartId,OprDepart,'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}',getdate() from house_baseinfo left join v_Hr_DepartmentInfo on(v_Hr_DepartmentInfo.departid= house_baseinfo.CompanyId) where HouseId in ('{16}');", model.NowPersonID.ToString(), model.NowPerson, model.NowCityId.ToString(), model.NowCity, model.NowCompanyId.ToString(), model.NowCompany, model.NowDepartID.ToString(), model.NowDepart, CurrentUserInfo.UserId.ToString(), CurrentUserInfo.UserName, CurrentUserInfo.CityId.ToString(), CurrentUserInfo.CityName, CurrentUserInfo.CompanyId.ToString(), CurrentUserInfo.CompanyName, CurrentUserInfo.DepartId.ToString(), CurrentUserInfo.DepartName, houseid);
         //添加房源的客户分配日志并修改客户记录
         strSql += string.Format("update Customer_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',Customer_BaseInfo.CompanyId='{4}',Customer_BaseInfo.CompanyName='{5}',CityId='{7}',CityName='{8}' from dbo.Customer_BaseInfo inner join (select CustomerId from house_baseinfo where HouseId in ('{6}'))a on Customer_BaseInfo.CustomerId =a.CustomerId;", model.NowPerson, model.NowPersonID.ToString(), model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, houseid, model.NowCityId.ToString(), model.NowCity);

         strSql += String.Format("update House_BaseInfo set OprPerson='{0}',OprPersonId='{1}',OprDepart='{2}',OprDepartId='{3}',CompanyId='{4}',CompanyName='{5}',CityId='{6}' where HouseId in ('{7}');", model.NowPerson, model.NowPersonID.ToString(), model.NowDepart, model.NowDepartID.ToString(), model.NowCompanyId.ToString(), model.NowCompany, model.NowCityId.ToString(), houseid);


         bool flag = Chenxin.Lib.House.DAL.House_BaseInfo.ExecuteSQL(strSql);
         if (flag)
             return 0;
         else
             return 1; 
     }
    
    //得到手动分配 房源的数据
     private string gethouselist(HttpContext context)
     {
         try
         {
            //string allotType = context.Request["allotType"];
             string allot_person = context.Request["OldPersonID"];
             string allot_dep = context.Request["OldDepartID"];
            string startDay = context.Request["startDay"];
            string endDay = context.Request["endDay"];
            string keyword = context.Request["keyword"];

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 5 : int.Parse(context.Request["pagesize"]);//页记录数
            string fieldlist = "HouseId,Adddate,HouseCode,Community,OprPerson,OprDepart";
            string fieldtablelist = "HouseId,CONVERT(varchar(12) , Adddate, 111 ) as Adddate,HouseCode,isnull(Community,'')+isnull(BuildingName,'')+isnull(Room,'') as Community,OprPerson,OprDepart";
            string orderfield = "House_BaseInfo.Adddate desc";

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("1=1");
             
            
            if (!string.IsNullOrEmpty(allot_person))
            {
                sb.Append(string.Format(" AND OprPersonId='{0}' and OprDepartId='{1}'", (allot_person),allot_dep));
            }
            if (!string.IsNullOrEmpty(startDay))
            {
             sb.Append(string.Format(" AND convert(varchar(10),(convert(datetime,Adddate,120)),120)  >= '{0}'", (startDay)));
            }
            if (!string.IsNullOrEmpty(endDay))
            {
             sb.Append(string.Format(" AND convert(varchar(10),(convert(datetime,Adddate,120)),120)  <= '{0}'", (endDay)));
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                sb.AppendFormat(" AND (DetailAddress Like '%{0}%' Or HouseCode Like '%{0}%' or Community Like '%{0}%')", keyword);
            } 

            System.Data.DataSet ds = null;
            ds = Chenxin.Lib.House.DAL.House_BaseInfo.GetList(iPageIndex, iPageSize, orderfield, "House_BaseInfo", sb.ToString(), fieldlist, fieldtablelist, true);
            int count = (int)ds.Tables[1].Rows[0][0];
            string strHtml = "";
            if (!GetListHtml(ds, out strHtml))
            {
             return string.Format("{{success:'0',msg:'{0}',data:''}}", "生成HTML错误");
            }
            ds.Dispose();
            ds = null;
            return string.Format("{{success:'1',msg:'{0}',data:{{count:'{1}',data:'{2}'}}}}", "成功", count, strHtml);
         }
         catch (Exception ex)
         {
             return string.Format("{{success:'0',msg:'{0}',data:''}}", "未知错误：" + ex.Message);
         }
     }

     /// <summary>
     /// 生成列表
     /// </summary>
     /// <param name="dslist"></param>
     /// <param name="strHtml"></param>
     /// <returns></returns>
     private bool GetListHtml(System.Data.DataSet dslist, out string strHtml)
     {
         System.Text.StringBuilder sb = new System.Text.StringBuilder();

         sb.Append("<table  class=\"PublicTable\" id=\"table_pt\" width=\"100%\" ><tr class=\"toolbar\"><th><input type=\"checkbox\" name=\"checkall\" id=\"checkall\" /></th><th>建档日期</th><th>房源编号</th><th>房源地址</th><th>业务员</th><th>门店</th></tr>");
         foreach (System.Data.DataRow row in dslist.Tables[0].Rows)
         {
             sb.Append(String.Format("<tr><td><input type=\"checkbox\" name=\"allotck\" value=\"{0}\"/></td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td></tr>", row["HouseId"], row["Adddate"], row["HouseCode"], row["Community"], row["OprPerson"], row["OprDepart"]));
         }
         sb.Append("</table>");
         strHtml = sb.ToString();
         return true;
     }

}